package cn.chendd.patch.ui.adapters.impls;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import cn.chendd.utils.LogUtil;

public class SrcImpl extends PathAdapter {

	public SrcImpl(String compileFolder , String regex , File dstFolder , String path) {
		super(compileFolder , regex , dstFolder , path);
	}

	@Override
	public void patchByPath() throws IOException {
		LogUtil.info(getClass().getSimpleName() + "实现匹配路径：" + path);
		path = "WEB-INF" + File.separator + "classes" + File.separator + path.substring(regex.length());
		File srcFile = new File(compileFolder , path);
		//如果是个目录，则创建
		if(srcFile.isDirectory()){
			File newFile = new File(dstFolder , path);
			newFile.mkdirs();
			return ;
		}
		//如果是以.java结尾的文件，则需要考虑匿名内部内的形式
		if(path.toLowerCase().endsWith(".java")){
			File javaFile = new File(dstFolder , path);
			final String fileName = FilenameUtils.getBaseName(javaFile.getName());
			File classesFile[] = srcFile.getParentFile().listFiles(new FilenameFilter() {
				@Override
				public boolean accept(File file, String name) {
					if(name.equals(fileName + "$.class")){
						return false;
					}
					//String rg = "^" + fileName + "[\\$\\d]*?\\.class";
					///String rg = "^" + fileName + "(\\$(\\d+))?\\.class";
					String rg = "^" + fileName + "(\\$(\\w|\\$)+)*\\.class";
					Matcher m = Pattern.compile(rg).matcher(name);
					return m.find();
				}
			});
			if(classesFile != null) {
				for (File file : classesFile) {
					File newFile = new File(dstFolder , path);
					copyFile(file, new File(newFile.getParentFile() , file.getName()));
				}
			}
		} else {
			File newFile = new File(dstFolder , path);
			if(srcFile.exists()) {
				copyFile(srcFile, newFile);
			}
		}
	}

	public void copyFile(File srcFile, File dstFile) throws IOException {
		//否则直接拷贝文件至新目录
		FileUtils.copyFile(srcFile, dstFile);
	}

	@Override
	public boolean patchFilterRule() {
		return path.startsWith(regex);
	}
	
}
